﻿
function filtersSelect(locationClass, agencyClass, mediaClass) {
	$(".left_menu_filter").hide();
	$(".tree_childs").hide();

	$(".filter_title, .filter_title_active").click(function () {
		$(this).next(".left_menu_filter").slideToggle(400);
	});

	$(".collapsable_tree").click(function () {
		$(this).next(".tree_childs").slideToggle(400);
		
		$("#" + $(this).attr('id') + '_arrowImageClosed').toggle();
		$("#" + $(this).attr('id') + '_arrowImageOpen').toggle();
	});

	//To put the correct images when item is selected
	$(".filter_item_selected").each(function () {
		$("#" + $(this).attr('id') + '_selectedImage').show();
		$("#" + $(this).attr('id') + '_unselectedImage').hide();
	});

	checkFilterButtonGlow();
}

function checkFilterButtonGlow() {

	if ($(".filter_title_active").length > 0) {
		$("#filtersButtonImage").hide();
		$("#filtersButtonImageGlow").show();
	}
	else { 
		$("#filtersButtonImage").show();
		$("#filtersButtonImageGlow").hide();
	}
}

function filtersTreeView(className) {
	$('.' + className)
		.jstree({ "plugins": ["themes", "html_data"] })
}

function filtersResetAll(itemType, urlAction, jsonObject) {

    showLoading();
    BeforeItemFIlterCall();

	resetAllByType(locationClass);
	resetAllByType(agencyClass);
	resetAllByType(mediaClass);

	checkFilterButtonGlow();

	var data = { 'filterType': itemType, 'jsonToggles': jsonObject };
	actionAsyncCall(data, urlAction, 'html', 'filterable_data_container',
                function () {
                    OnFilterCompleted();
                    if (!manageFilterLoadingExternal)
                    {
                        hideLoading();
                    }
                },
                function () { hideLoading(); });
}

function resetAllByType(classType) {
	$("." + classType + ".filter_title_active:not(filter_fixed)").each(function () {
	
		//desactivate the filter title
		$(this).removeClass('filter_title_active').addClass('filter_title');
        
		$(".filter_item_selected." + classType).each(function () {
		    unselectItem($(this));
		});

		$(".filter_isAll.filter_isRoot.filter_item." + classType).each(function () {
			selectItem($(this));
		});
	});
}

function getClassType(itemType)
{
	var classType = "";
	//ClassID types variables are defined in "_Filtes.cshtml" file
	switch (itemType) {
		case locationClassID:
			classType = locationClass;
			break;
		case agencyClassID:
			classType = agencyClass;
			break;
		case mediaClassID:
			classType = mediaClass;
			break;
	}
	return classType;
}

 function filterItemSelectChange(obj, itemType, itemID, urlAction, jsonObject) {
     if (!obj.hasClass('clickeable'))
         return;

    showLoading();
    BeforeItemFIlterCall();
	
	var isSelected = false;
	var classType = getClassType(itemType);
	//Update the view item
	if (obj.hasClass('filter_item')) { //On selected
		isSelected = true;
		selectItem(obj);

		//activate the parent title
		if (!obj.hasClass('filter_isRoot')) {
			recursiveParentActive(obj.attr('data-parentid'));
			$(".filter_title." + classType).removeClass('filter_title').addClass('filter_title_active');
			selectItem(obj);
			if (obj.hasClass('filter_isAll')) {
			    unselectAllChildren(obj);
            }
		}
		else {// Selecting All Root
			selectItem(obj);
			unselectAllChildren(obj);
			//deactivate the parent title if All is root
			if (obj.hasClass('filter_isRoot'))
				$(".filter_title_active." + classType).removeClass('filter_title_active').addClass('filter_title');
		}

	 } else { //On Unselectn 
		 if (!obj.hasClass('filter_isRoot')) {
			 unselectItem(obj);
		 }

		 recursiveParentInactive(obj.attr('data-parentid'));

		 if (obj.hasClass('filter_isAll')) {
			 recursiveAllUselected(obj, classType);
		 }
		 else {
			 recursiveItemUselected(obj, classType);
		 }
	}

    var data = { 'filterType': itemType, 'jsonToggles': jsonObject, 'itemID': itemID, 'isSelected': isSelected };
    actionAsyncCall(data, urlAction, 'html', 'filterable_data_container',
                function () {
                    OnFilterCompleted();
                    if (!manageFilterLoadingExternal)
                    {
                        hideLoading();
                    }
                },
                function () { hideLoading(); });

	checkFilterButtonGlow();
}

function selectItem(item) {
	$("#" + item.attr('id') + "_unselectedImage").hide();
	$("#" + item.attr('id') + "_selectedImage").show();

	item.removeClass('filter_item').addClass('filter_item_selected');
}

function unselectItem(item) {
	$("#" + item.attr('id') + "_unselectedImage").show();
	$("#" + item.attr('id') + "_selectedImage").hide();

	item.removeClass('filter_item_selected').addClass('filter_item');
}

function showModalDialogDataError(errorMessages, itemType) {
	var errorMessage = '';
	for (var i = 0; i < errorMessages.length; i++) {
		errorMessage = errorMessage + '<br><br>' + errorMessages[i];
	}
	$("div#divModalTextError").html(errorMessage);
	var classType = getClassType(itemType);
	resetAllByType(classType);


	$("#divModalTextError").show();


	setTimeout(function () {
	    $("div#divModalDialogDataError").fadeOut(1000, function () {
	        $("#divModalTextError").hide();
	    });
	}, 5000); //time is in miliseconds
    

	/*
	    if (window.location.href.indexOf('#') == -1)
	        window.location.href = window.location.href + "#divModalDialogDataError";
	    else
	        window.location.href = window.location.href + "divModalDialogDataError";
	
        setTimeout(function () {
	        $("div#divModalDialogDataError").fadeOut(1000, function () {
	            window.location.href = '#';
	            $("div#divModalDialogDataError").removeAttr('style');
	        });
	    }, 5000); //time is in miliseconds
    */

	hideLoading();
}

//This funtion is called when updating the data on a chart makes some filter state to change
function filterItemOnChange(itemID, itemState) {
	var itemClasses = '';
	var itemRemoveClasses = '';
	switch (itemState) {
		case filterStateEnableID: //available
		    itemRemoveClasses = 'filter_item_disable filter_item_no_data';
		    itemClasses = 'clickeable';
			break;
		case filterStateNoDataID: //no data for that filter -> gray out
			itemClasses = 'filter_item_no_data';
			itemRemoveClasses = 'filter_item_selected filter_item_disable clickeable';
			break;
		case filterStateDisableID: //disable because of permitions -> black out
			itemClasses = 'filter_item_disable';
			itemRemoveClasses = 'filter_item_selected filter_item_no_data clickeable';
			break;
	}
	$("div#" + itemID).removeClass(itemRemoveClasses).addClass(itemClasses);

	checkFilterButtonGlow();
}

function recursiveParentActive(idParent) {

	var idGrandParent = $("#" + idParent).attr('data-parentid');

	if (typeof idGrandParent !== 'undefined' && idGrandParent !== false) {
		recursiveParentActive(idGrandParent);
	}

	$(".filter_item_selected.filter_isAll[data-parentid='" + idParent + "']").each(function (){ 
		unselectItem($(this))
	});

	if (!$("#" + idParent).hasClass('filter_item_selected')) {
		selectItem($("#" + idParent));
	}
}

function recursiveAllUselected(item, classType) {
	var me = $(item);
	var isRoot = me.hasClass('filter_isRoot');
	if (isRoot) {
		resetAllByType(classType);
	}
	else {        
		unselectItem(me);
		var idGrandParent = $('#' + me.attr('data-parentid')).attr('data-parentid');
		var parentSiblins = $(".filter_item_selected[data-parentid='" + idGrandParent + "']")
		//If there is not any item selected on this level, we should move up to the next on
		if (parentSiblins.length == 0) {
			var allItem_ParentSiblin = $(".filter_isAll[data-parentid='" + idGrandParent + "']");
			recursiveAllUselected(allItem_ParentSiblin, classType);
		}
	}
}

function recursiveItemUselected(item, classType) {
	var me = $(item);
	var isRoot = me.hasClass('filter_isRoot');
	if (isRoot) {
		resetAllByType(classType);
	}
	else {
		unselectItem(me);
		var idParent = me.attr('data-parentid');
		var parentSiblins = $(".filter_item_selected[data-parentid='" + idParent + "']")
		//If there is not any item selected on this level, we should move up to the next on
		if (parentSiblins.length == 0) {
			var allItem_ParentSiblin = $(".filter_isAll[data-parentid='" + idParent + "']");
			recursiveAllUselected(allItem_ParentSiblin, classType);
		}
	}
}

function recursiveParentInactive(idParent) {
	
	var anySubChilds = $(".filter_item_selected[data-parentid='" + idParent + "']");

	if (anySubChilds.length == 0) {
		unselectItem($("#" + idParent));
	}

	var idGrandParent = $("#" + idParent).attr('data-parentid');
	if (typeof idGrandParent !== 'undefined' && idGrandParent !== false) {
		recursiveParentInactive(idGrandParent);     
	}
}

//This function must be called when an "All" item is selected, the allItem should be called
function unselectAllChildren(allItem) {
	var idParent = allItem.attr('data-parentid');
	$(".filter_item_selected:not(.filter_isAll)[data-parentid='" + idParent + "']").each(function () {
	    recursiveChildsUnselect(this);
	});
}

//This function must be called when an "All" item is selected, the parentId should be sent
function recursiveChildsUnselect(node) {
	var nodeId = $(node).attr('id');
	$(".filter_item_selected[data-parentid='" + nodeId + "']").each(function () {
		recursiveChildsUnselect(this);
    });

    unselectItem($(node));
}

/******************************************************/
//Functions to be overriden
function OnFilterCompleted() {}

function BeforeItemFIlterCall() {}

/******************************************************/




//This is used in case of Filters hideLoading should not be used when OnSuccess
var manageFilterLoadingExternal = false;


//////////////// TOGGLES SECTION BEGIN /////////////////

function togglesSelectChange(jsonObject, urlAction, resultContainerId, functionOnSuccess) {
    showLoading();

    var data = { 'jsonToggles' : jsonObject };
    actionAsyncCall(data, urlAction, 'html', resultContainerId,
            function () {  
                hideLoading();
                if (functionOnSuccess != null) {
                    functionOnSuccess();
                } 
            }, 
            function() {  hideLoading(); });
}

function actionAsyncCall(data, urlAction, dataType, resultContainerId, functionOnSuccess, functionOnError, functionOnComplete) {
    $.ajax({
        type: 'POST',
        url: urlAction,
        data: data,
        dataType: dataType,
        success: function (result) {
            if (resultContainerId != null) {
                var container = $('#' + resultContainerId);
                if (container.length > 0) {
                    container.html(result);
                }
            }
            if (functionOnSuccess != null) {
                functionOnSuccess(result);
            }
        },
        error: function (err, result) {
            //ToDo: handle error
            alert('Error: ' + err + ' Result: ' + result);
            if (functionOnError != null) {
                functionOnError(err);
            }
        },
        complete: function () {
            if (typeof functionOnComplete !== 'undefined' && functionOnComplete != null) {
                functionOnComplete();
            }
        }
    });
}

// Enable selected toggle and disable the rest of toggles
// chkIds: sorted array with ckeckbox ids
// tooglesId : sorted array with toogle div ids
function activeCheckboxToggle(idSelectedToggleChk, chkIds, tooglesIds, enableClassName, disableClassName) {
    var len = chkIds.length;
    for (var i = 0; i < len; i++) {
        if (idSelectedToggleChk != chkIds[i]) {
            $('#' + chkIds[i]).attr('checked', false);
            $('#' + tooglesIds[i]).attr("class", disableClassName);
        }
        else {
            $('#' + chkIds[i]).attr('checked', true);
            $('#' + tooglesIds[i]).attr("class", enableClassName);
        }
    }
}

function changeToggle(idToggleSelected, idToggleUnselected) {
    $("#" + idToggleSelected).toggleClass('toggleDisabled').toggleClass('toggleEnabled');
    $("#" + idToggleUnselected).toggleClass('toggleDisabled').toggleClass('toggleEnabled');
}

function changeLonelyToggle(idSelectedToggle) {
    $("#" + idSelectedToggle).toggleClass('lonelyToggleEnabled').toggleClass('lonelyToggleDisabled');
}

function changeImageToggle() {
    var toggleClass = $("#toggleChart").attr("class");
    var imageSrc = '@Url.Content("~/Content/images/bars.png")';
    if (toggleClass.search("toggleEnabled") != -1) {
        imageSrc = '@Url.Content("~/Content/images/barsGlowed.png")';
    }

    $("#imgBars").attr("src", imageSrc);
}

//////////////// TOGGLES SECTION END /////////////////
